<template>

	<view>
		<view class="page">
			<view class="cardView">
				<!-- 工单类型选择 -->
				<uni-forms ref="baseForm" label-position="top">
					<uni-title type="h2" title="选择工单类型" align="center"></uni-title>
					<uni-forms-item label="工单分类" required>
						<uni-data-select v-model="selectedType" :localdata="orderTypeItem"
							@change="typechange"></uni-data-select>
					</uni-forms-item>
					<uni-forms-item label="时间范围" required>
						<uni-row class="example-uni-row">
							<uni-col :span="12">
								<uni-datetime-picker v-model="startTime" placeholder="开始时间" type="date"
									:clear-icon="true" fields="day" @change="timeChange"></uni-datetime-picker>
							</uni-col>
							<uni-col :span="12">
								<uni-datetime-picker v-model="endTime" placeholder="结束时间" type="date" :clear-icon="true"
									fields="day" @change="timeChange"></uni-datetime-picker>
							</uni-col>
							</uni-col>
						</uni-row>
					</uni-forms-item>
					<button type="primary" @click="handleQuery">查询</button>
				</uni-forms>
			</view>
			<!-- 动态加载分析组件 -->
			<component :start-time="startTime" :end-time="endTime" :is="currentComponent" :type="selectedType" />

		</view>
		<view class="button-container">
			<view class="button-save">
				<button type="primary">打印数据表单</button>
			</view>
			<view class="button-save">
				<button type="warn" class="button-save" @click="gohome">返回首页</button>
			</view>

		</view>

	</view>

</template>

<script>
	import businessTableGroup from './components/business-table-group.vue'
	import businessTable from './components/business-table.vue'
	import demodata from '@/mockdata/demodata.json';
	import BusinessAnalysis from './components/business-analysis.vue'
	import MedicalAnalysis from './components/medical-analysis.vue'
	import ProductionAnalysis from './components/production-analysis.vue'

	import {
		getMedicalDict,
	} from '@/api/order'
	export default {
		components: {
			businessTable,
			BusinessAnalysis,
			businessTableGroup,
			MedicalAnalysis,
			ProductionAnalysis
		},
		data() {

			return {
				selectedType: null, // 默认选中第一个类型
				startTime: '',
				endTime: '',
				currentComponent: null,
				orderTypeItem: {}
			}
		},
		onLoad() {
			this.getMedicalDict('order_type')
		},
		watch: {
			selectedType(newVal) {
				console.log("newVal+" + newVal)
				switch (newVal) {
					case '1':
						this.currentComponent = 'BusinessAnalysis';
						break;
					case '2':
						this.currentComponent = 'ProductionAnalysis';
						break;
					case '3':
						this.currentComponent = 'MedicalAnalysis';
						break;
				}
			}
		},
		methods: {
			validateTime() {
				if (!this.startTime || !this.endTime) {
					uni.showToast({
						title: '请选择完整时间范围',
						icon: 'none'
					})
					return false
				}
				if (moment(this.endTime).isBefore(this.startTime)) {
					uni.showToast({
						title: '结束时间不能早于开始时间',
						icon: 'none'
					})
					return false
				}
				return true
			},
			handleQuery() {
				if (!this.validateTime()) return
				// 强制重新加载子组件（可选方案一）
				this.currentComponent = null
				this.$nextTick(() => {
					this.currentComponent = this.getComponentType(this.selectedType)
				})


			},
			getComponentType(type) {
				switch (type) {
					case '1':
						return 'BusinessAnalysis'
					case '2':
						return 'ProductionAnalysis'
					case '3':
						return 'MedicalAnalysis'
					default:
						return null
				}
			},
			//获取字典值
			async getMedicalDict(type) {

				try {
					const res = await getMedicalDict(type)
					// 增加响应状态判断
					if (res.code === 0) { //获取经营项目方法
						if (type === 'order_type') {
							this.orderTypeItem = res.data.map(item => ({
								text: item.label,
								value: item.value // 确保转换为数字类型
							}));

							// 设置默认选中第一个选项
							if (this.orderTypeItem.length > 0) {
								this.selectedType = this.orderTypeItem[0].value
								console.log('初始化selectedType:', this.selectedType)
							}
						} else {
							throw new Error(res?.data?.msg || '接口返回异常')
						}
					}
				} catch (error) {
					uni.showToast({
						title: error.message || '获取失败',
						icon: 'none',
						duration: 2000
					})
				}
			},

			gohome() {
				this.$tab.reLaunch('/pages/work/index')
			},
			typechange(e) {
				this.selectedType = e // 如果v-model未生效可手动赋值
				console.log('工单类型变更:', e);
			},
		}
	}
</script>

<style lang="scss">
	.page {
		background-color: #e9f1fe;
		padding: 20px;
		height: 100%;
	}

	.cardView {
		margin-bottom: 10px;
		padding: 15px;
		background: #ffffff;
		border-radius: 8px;
		box-shadow: 0 2px 12px rgba(0, 0, 0, 0.12);
	}

	.charts-box {
		width: 90vw;
		height: 10vh;
		min-height: 300rpx;
		/* 兼容小程序 */
	}

	.button-container {
		display: flex;
		background-color: #ffffff;
		width: 100%;
		padding: 10px;
		flex-direction: column;
		/* 垂直排列 */

		.button-save {
			margin-bottom: 10px;
		}

		.button-child {
			display: flex;
			flex-direction: row;
			/* 垂直排列 */

		}
	}
</style>